#include "draghandler.h"

DragHandler::DragHandler(QWidget *parent)
    : QObject(parent), m_parentWidget(parent)
{}

bool DragHandler::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == m_parentWidget)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            return mousePressEvent(static_cast<QMouseEvent*>(event));
        }
        else if (event->type() == QEvent::MouseMove)
        {
            return mouseMoveEvent(static_cast<QMouseEvent*>(event));
        }
        else if (event->type() == QEvent::MouseButtonRelease)
        {
            return mouseReleaseEvent(static_cast<QMouseEvent *>(event));
        }
    }
    return QObject::eventFilter(watched, event);
}

bool DragHandler::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = true;
        m_dragPosition = event->globalPosition().toPoint() - m_parentWidget->frameGeometry().topLeft();
        // 按下鼠标左键时，设置光标为 "手形"（移动光标）
        m_parentWidget->setCursor(Qt::SizeAllCursor);
        event->accept();
        return true;
    }
    return false;
}

bool DragHandler::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging)
    {
        m_parentWidget->move(event->globalPosition().toPoint() - m_dragPosition);
        event->accept();    // 阻止事件向父控件传递
        return true;
    }
    return false;
}

bool DragHandler::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_dragging = false;
        // 鼠标释放时，恢复光标为默认形态
        m_parentWidget->setCursor(Qt::ArrowCursor);
        event->accept();
        return true;
    }
    return false;
}
